package dao;

import pojo.Book;
import pojo.Category;
import util.JDBCUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tiler on 2020/11/5
 */
public class RelationDaoImpl implements RelationDao {
    @Override
    public List<Category> selectCategoriesByBid(Integer bookId) {
        String sql = "select c.* from category c inner join relation r on r.categoryId = c.categoryId where r.bookId = ?";

        List<Category> categories = new ArrayList<>();

        JDBCUtil jdbcUtil = new JDBCUtil();

        ResultSet resultSet = jdbcUtil.excuteQuery(sql, bookId);

        try {
            while(resultSet.next()) {
                Category category = new Category();

                category.setCategoryId(resultSet.getInt("categoryId"));
                category.setCategoryName(resultSet.getString("categoryName"));

                categories.add(category);
            }

            return categories;
        } catch (SQLException e) {
            e.printStackTrace();

            return null;
        }
        finally {
            jdbcUtil.close();
        }
    }

    @Override
    public Integer insertBookCategories(Integer bookId, List<Integer> categories) {
        Integer row = categories.size();

        Integer[][] params = new Integer[row][2];

        for (int i = 0; i < row; i++) {
            params[i][0] = bookId;
            params[i][1] = categories.get(i);

            System.out.println(params[i][0] + " " + params[i][1]);
        }

        Integer status = 1;

        JDBCUtil jdbcUtil = new JDBCUtil();

        String sql = "insert into relation(bookId, categoryId) values (?, ?)";

        int[] result = jdbcUtil.excuteBatch(sql, params);
        for (int i : result) {
            if (i <= 0) {
                status = 0;
                break;
            }
        }

        jdbcUtil.close();

        return status;
    }

    @Override
    public Integer deleteCategoriesByBid(Integer bookId) {
        JDBCUtil jdbcUtil = new JDBCUtil();

        String sql = "delete from relation where bookId = ?";

        Integer status = jdbcUtil.excuteUpdate(sql, false, bookId);

        jdbcUtil.close();

        return status;
    }
}
